import React,{useEffect} from 'react'
import {Navigate,useNavigate} from 'react-router-dom'
import $http from '../api/http'
import {message} from 'antd'
export default function AuthComponent({children}) {
  const nav=useNavigate()
  const getUserInfo=async()=>{
    try {
      await $http.users.getUserInfo()
    } catch (error) {
      switch(error.response.status){
        case 401:
          message.warning('您的token已经失效，请重新登录')
          nav('/login',{replace:true})
          break
      }
    }
  }
  useEffect(()=>{
    getUserInfo()
  },[])
  //判断token是否存在
  const isAuth=!!localStorage.getItem('token')
  if(isAuth){
    return <>{children}</>
  }else{
    message.warning('您没有token，请登录后在进入系统')
    return <Navigate to={"/login"}></Navigate>
  }
}
